//
//  ZAQStatusPictureView.swift
//  ZAQWBDZT
//
//  Created by 赵安庆 on 16/9/25.
//  Copyright © 2016年 zaq. All rights reserved.
//

import UIKit
import SDWebImage
private let ZAQStatusPictureViewCellIdentifier = "ZAQStatusPictureViewCellIdentifier"

//  每项之间的间距
let itemMargin: CGFloat = 5
//  每项的宽度
let itemWidth = (ScreenWidth - 2 * HMHomeTableViewCellMargin - 2 * itemMargin) / 3
class ZAQStatusPictureView: UICollectionView {

    //  设置配图数据源
    var picUrls: [ZAQStatusPictureInfo]? {
        didSet {
//            messageLabel.text = "\(picUrls?.count ?? 0)"
            messageLabel.text = "\(picUrls?.count ?? 0)"

            let size = calcSize(count: picUrls?.count ?? 0)

            //  设置约束大小
            self.snp_updateConstraints { (make) in
                make.size.equalTo(size)
            }
            self.reloadData()
        }
    }
    //  MARK: --懒加载控件
    private lazy var messageLabel: UILabel = {
        let label = UILabel(textColor: UIColor.magenta, fontSize: 20)
        return label
    }()
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //  创建布局对象
        let flowLayout = UICollectionViewFlowLayout()

        //  设置大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //  垂直间距
        flowLayout.minimumLineSpacing = itemMargin
        //  水平间距
        flowLayout.minimumInteritemSpacing = itemMargin


        super.init(frame: frame, collectionViewLayout: flowLayout)

        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI() {
//        backgroundColor = RandomColor()
        backgroundColor = UIColor(white: 1, alpha: 1)
        //  注册cell
        register(ZAQStatusPictureViewCell.self, forCellWithReuseIdentifier: ZAQStatusPictureViewCellIdentifier)
        //  设置数据源代理
        self.dataSource = self
        self.delegate = self
        addSubview(messageLabel)

        messageLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self)
        }
    }
    private func calcSize(count: Int) -> CGSize {

        if count == 1{
           let imgUrl = picUrls?.first?.thumbnail_pic

           let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: imgUrl)
            if image != nil{
                var size = image!.size
                size = CGSize(width: itemWidth, height: itemWidth)

                let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout

                flowLayout.itemSize = size
                return size
            }


        }

        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout

        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)

  //  计算列数
        let cols = count > 3 ? 3 : count
        //  计算行数
        let rows = (count - 1) / 3 + 1
        //  计算当前配图宽度
        let currentWidth = itemWidth * CGFloat(cols) + CGFloat(cols - 1) * itemMargin
        //  计算当前配图的高度
        let currentHeight = itemWidth * CGFloat(rows) + CGFloat(rows - 1) * itemMargin

        return CGSize(width: currentWidth, height: currentHeight)

    }

}
//  MARK: --数据源方法
extension ZAQStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate, SDPhotoBrowserDelegate {
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
                return  picUrls?.count ?? 0
            }

       func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZAQStatusPictureViewCellIdentifier, for: indexPath) as! ZAQStatusPictureViewCell
//                cell.backgroundColor = RandomColor()
        cell.statusPictureInfo = picUrls![indexPath.item]
                return cell
            }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = picUrls!.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
    }
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        let cell = self.cellForItem(at: IndexPath(item: index, section: 0)) as! ZAQStatusPictureViewCell
        return cell.imageView.image
    }

    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let urlStr = picUrls![index].thumbnail_pic!.replacingOccurrences(of: "thumbnail", with: "bmiddle")
        return URL(string: urlStr)
    }
}

//  自定义配图cell
class ZAQStatusPictureViewCell: UICollectionViewCell {
    //  设置模型数据
    var statusPictureInfo: ZAQStatusPictureInfo? {
        didSet {
            if let url = statusPictureInfo?.thumbnail_pic {
                imageView.sd_setImage(with: URL(string: url), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                //  判断后缀是否是.gif
                if url.hasSuffix(".gif") {
                    gifImageView.isHidden = false
                } else {
                    gifImageView.isHidden = true
                }

            }
        }
    }
    //  MARK: --    懒加载控件
    lazy var imageView: UIImageView = {

        let view = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //  等比例原样显示
        view.contentMode = .scaleAspectFill
        //  会有超出范围显示,  剪切多余部分
        view.clipsToBounds = true
        return view
    }()
    //  gif图片
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //  添加控件设置约束
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)

        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsets.zero)
        }
        gifImageView.snp_makeConstraints { (make) in
            make.bottom.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }

    }

}
